import router from '../router'
import { Message, Notification } from 'element-ui'

const API_URL = '/api';

const getToken = () => {
  return sessionStorage.token;
}

const _getOptions = (data, url = '') => {
  return {
    method: 'post',
    url: API_URL + url,
    headers: {
      'Content-Type': 'application/json',
    },
    data: data
  }
}

const post = async (data, url) => {
  const options = _getOptions(data, url);
  return await _post(options);
}

const postWithToken = async (data) => {
  const options = _getOptions(data);
  options.headers.Authorization = 'Bearer ' + getToken();

  return await _post(options);
}

const _post = async (options) => {
  try {
    console.log(options);

    let result = await axios(options);

    result = result.data;

    if (result.rescode == 99) {
      router.push('/login');
    }

    if (result.rescode != 0) {
      const content = `业务请求失败，原因：${result.resdesc}`;
      throw content;
    }
    return result;
  } catch (error) {
    Notification({
      message: error,
      type: 'error',
    });
    console.log(error);
    throw error;
  }
}

export default {
  post,
  postWithToken
}

